package com.good.cm.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Md5Utils {
    public static String encode(String msg) {

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("md5");
            //return Base64.getEncoder().encodeToString(messageDigest.digest(msg.getBytes()));
            return messageDigest.digest(msg.getBytes()).toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String stringToMD5(String plainText) {
        byte[] mdBytes = null;
        try {
            mdBytes = MessageDigest.getInstance("MD5").digest(plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不存在!");
        }
        String mdCode = new BigInteger(1, mdBytes).toString(16);
        if (mdCode.length() < 32) {
            int a = 32 - mdCode.length();
            for (int i = 0; i < a; i++) {
                mdCode = "0" + mdCode;
            }
        }
       return mdCode.toUpperCase();//返回32位大写
    }
}
